<?php

namespace app\admin\controller\health\tracking;

use app\common\controller\Backend;
use app\health\model\HealthUser;
use app\health\model\HealthUserChannel;
use app\health\model\tracking\HealthTrackingUserRemain;

class UserRemain extends Backend
{
    public function index()
    {
        if ($this->request->isAjax()) {
            $data             = [];
            $startDate        = strtotime('-13 day');
            $endDate          = time();
            $userRemainColumn = HealthTrackingUserRemain::whereTime('created_at', 'between', [$startDate, $endDate])
                ->group('date')
                ->column('STR_TO_DATE(`created_at`,"%Y-%m-%d") as date,count(*) as total');
            $days_column      = [];
            for ($currentDate = $startDate; $currentDate <= $endDate; $currentDate += 86400) {
                $day           = date('Y-m-d', $currentDate);
                $days_column[] = ['day' => $day, 'total' => $userRemainColumn[$day] ?? 0];
            }
            $userAll       = HealthUser::all();
            $userTotal     = 0;
            $userAuthTotal = 0;
            foreach ($userAll as $user) {
                $userTotal++;
                if (!empty($user['id_card'])) {
                    $userAuthTotal++;
                }
            }
            $data['days_column']       = $days_column;
            $data['user_total']        = $userTotal;
            $data['user_auth_total']   = $userAuthTotal;
            $data['user_auth_percent'] = number_format(($userAuthTotal / $userTotal), 2);
            $this->success('success', '', $data);
        }
        return $this->view->fetch();
    }

    /**
     * 用户渠道统计
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function channel()
    {
        $data           = [];
        $userChannel    = HealthUserChannel::group('channel_id')
            ->with(['popularize'])
            ->field('channel_id,count(1) as total')
            ->select();
        $channelTypeMap = ['other' => '其它', 'h5' => '落地页', 'sms' => '短信营销'];
        foreach ($userChannel as $item) {
            $channelType = empty($item['popularize']) ? 'other' : $item['popularize']['channel_type'];
            if (isset($data[$channelType])) {
                $data[$channelType]['total'] += $item['total'];
            } else {
                $data[$channelType] = [
                    'channel_name' => $channelTypeMap[$channelType],
                    'total'        => $item['total']
                ];
            }
        }
        sort($data);
        $area = HealthUserChannel::group('city')->field('city as name,count(1) as value')->select();
        $this->success('success', '', ['channel' => $data, 'area' => $area]);
    }
}